import re

from django_redis import get_redis_connection
from rest_framework import serializers
# from rest_framework.settings import api_settings
from goods.models import SKU
from users.models import User, Address
from celery_tasks.mail.tasks import send_verify_mail
from rest_framework_jwt.settings import api_settings


# 历史记录查看序列化器
class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')


# 添加用户浏览记录
class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品编号',min_value=1,required=True)

    def validate_sku_id(self, value):
        # 检查商品是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):

        # 获取用户信息
        user_id = self.context['request'].user.id
        # 获取商品id
        sku_id = validated_data['sku_id']
        # 连接redis
        redis_conn = get_redis_connection('history')
        # 移除已经存在的本记录
        redis_conn.lrem('history_%s'%user_id,0,sku_id)
        # 添加新的记录
        redis_conn.lpush('history_%s'%user_id,sku_id)
        # 保存最多5条记录
        redis_conn.ltrim('history_%s'%user_id,0,4)
        return validated_data


# 用户地址标题
class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


# 用户地址新增与修改
class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


# 注册序列化器
class RegisterCreateSerializer(serializers.ModelSerializer):
    """
    注册序列化器
    """
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False,
                                     allow_blank=False,write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)
    # 增加token字段
    token = serializers.CharField(label='登录状态token', read_only=True)

    def create(self, validated_data):
        """创建用户"""
        # 重写create方法, 去掉数据库没有的自己创建的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        # 对明文密码进行加密
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token，替代session
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

    class Meta:
        model = User
        # 增加token
        fields = ('id','username','password','mobile','password2','sms_code','allow','token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 进行手机号码和是否同意协议的校验
    def validate_mobile(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号码不符合规则')

        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('没有同意协议规则')

        return True

    # 校验两次密码是否一致
    def validate(self, attrs):
        # 1 获取密码
        password = attrs['password']
        password2 = attrs['password2']
        # 2 比较密码
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')
        # 3 获取手机验证码
        inp_sms_code = attrs['sms_code']
        inp_mobile = attrs['mobile']
        # 4 获取数据库中手机验证码
        redis_conn = get_redis_connection('code')
        red_sms_code = redis_conn.get('sms_%s' % inp_mobile)
        if red_sms_code is None:
            raise serializers.ValidationError('验证码过期')
        # 对比两者密码
        if red_sms_code.decode() != inp_sms_code:
            raise serializers.ValidationError('验证码错漏')
        return attrs


# 用户详情信息
class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详情信息序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


# 邮箱序列化器
class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email':{
                'required':True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = validated_data['email']
        instance.save()

        # 发送激活邮件
        verify_url = instance.generate_verify_email_url()
        # 调用delay发送邮件
        send_verify_mail.delay(email,verify_url)
        return instance